let redis = require("redis");
//120.77.45.208
let redisClient = redis.createClient(6379, "127.0.0.1");
redisClient.auth("@");
redisClient.select(1, (err) => { })
redisClient.on("connect", function () {
  console.log(`Redis=>连接成功${new Date()}`);
});
redisClient.on("error", function (err) {
  console.log("Redis error: " + err);
});
module.exports = {
  get: async (key) => {
    let data = await new Promise((resolve) => {
      redisClient.get(key, function (err, res) {
        return resolve(res || "");
      });
    });
    ((key.indexOf("client_") !== -1) && !data) && console.error(`未获取到key为=>${key}${new Date()}`)
    return data.deJson();
  },
  set: async (name, value, time = 0) => {
    await new Promise((resolve) => {
      redisClient.ttl(name, function (r, b) {
        if (b !== -1 && b >= 0) (time = time || b);//如果不等于-1则续上之前得时间
        resolve(true);
      })
    })
    let data = await new Promise((resolve) => {
      redisClient.set(name, value, function (err, res) {
        return resolve(res || "");
      });
    });
    time && redisClient.expire(name, time);//设置过期时间
    return data
  },
  del: (name) => {
    return redisClient.del(name);
  },
  // 添加到list末位
  zadd: async (hname, value) => {
    let data = await new Promise((resolve) => {
      redisClient.zadd(hname, +new Date(), value, function (err, res) {
        resolve(res);
      });
    });
    return data;
  },
  //获取总长
  zcard: async (hname) => {
    let data = await new Promise((resolve) => {
      redisClient.zcard(hname, function (err, res) {
        resolve(res);
      });
    });
    return data;
  },
  //获取第一个元素
  zrange: async (hname) => {
    let data = await new Promise((resolve) => {
      redisClient.zrange(hname, 0, 0, function (err, [res]) {
        resolve(res || null);
      });
    });
    return data;
  },
  //移出指定元素
  zrem: async (hname, info) => {
    let data = await new Promise((resolve) => {
      redisClient.zrem(hname, info, function (err, res) {
        resolve(res);
      });
    });
    return data;
  },
  client: redisClient,
  logErrors: res => {
    console.error("Redis=>", res);
  }
};
